<template>
  <CompBox title="30日稼动率曲线">
    <div id="chart" style="height: 200px;width: 100%;margin-top: 57px"></div>
  </CompBox>
</template>

<script setup>
import CompBox from "@/views/screen/component/CompBox.vue"
import * as echarts from "echarts";
import {nextTick, onMounted, onUnmounted, ref} from "vue";
import {getUtilizeCurve} from "../../../api/business/screen";

const dataList = ref({})
const chartData = ref([])
const timer = ref()
onMounted(() => {
  initChart()
  initData()
  handleTask()
})
onUnmounted(()=>{
  clearInterval(timer.value)
})
function initData() {
  getUtilizeCurve().then((res) => {
    dataList.value = res.data
  })
}

function handleTask() {
// 定义每次需要取出的元素数量
  const elementsPerIteration = 2;
// 定义当前数组的索引
  let currentIndex = 0;
// 定义定时器
timer.value = setInterval(() => {
    // 取出指定数量的元素
    const elements = dataList.value.slice(currentIndex, currentIndex + elementsPerIteration);
    // 处理取出的元素
    chartData.value = elements
    nextTick(()=>{initChart()})

    // 更新当前索引
    currentIndex += elementsPerIteration;
    // 如果当前索引超过数组长度，则重置为0
    if (currentIndex >= dataList.value.length) {
      currentIndex = 0;
    }
    // 如果已经遍历完整个数组，清除定时器
    if (currentIndex === 0) {
      initData()
    }
  }, 3000);
}

function initChart() {
  // 初始化 echarts 实例
  const myChart = echarts.init(document.getElementById('chart'));

// 配置项
  const option = {
    legend: {
      data: chartData.value.map(device => device.name),
      textStyle: {
        color: '#fff'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'line'
      },
      formatter: function (params) {
        var result = params[0].value[0] + '<br/>';
        params.forEach(function (item) {
          result += item.seriesName + ': ' + item.value[1] + '%<br/>';
        });
        return result;
      }
    },
    xAxis: {
      type: 'category',
      boundaryGap: true,
      //data: Array.from({length: 30}, (_, i) => i + 1),
      name: '日期',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#fff'
        }
      },
      axisLabel: {
        rotate: 45,
        formatter: (value)=>{ return value.substring(5)}
      },
    },
    yAxis: {
      type: 'value',
      name: '稼动率 (%)',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#fff'
        }
      },
      splitLine: {
        show: false,
      }
    },
    series: chartData.value.map(device => ({
      type: 'line',
      data: device.curveData.map((item)=>{
        return [
            item.date,
            (item.utilization * 100).toFixed(2)
        ]
      }),
      name: device.name,
      smooth: true, // 是否平滑曲线
      symbol: 'none', // 不显示坐标点
      symbolSize: 0, // 坐标点大小设置为0
    })),
  };

// 使用刚指定的配置项和数据显示图表。
  myChart.setOption(option);
}
</script>

<style scoped>

</style>